package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    // 其中的id是要关注的用户id
    @Override
    public Result follow(Long id, Boolean isFollow) {
        // 1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        // 2.判断
        if (isFollow) {
            // 2.1 关注---添加一条记录
            Follow follow = new Follow();
            follow.setFollowUserId(id);
            follow.setUserId(userId);
            boolean isSuccess = save(follow);
            // 如果数据库操作成功,添加当前用户的关注用户到set集合
            if (isSuccess) {
                // 将这一条信息添加到set集合
                stringRedisTemplate.opsForSet().add(key, id.toString());
            }

        } else {
            // 2.2 取消关注---删除这一条记录
            // 需要判断是否查询得到follow对象
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", id));
            if (isSuccess) {
                // 从set集合中删除相关的记录
                stringRedisTemplate.opsForSet().remove(key, id.toString());
            }
        }
        // 3.返回
        return Result.ok();
    }


    @Override
    public Result isFollow(Long id) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
//        Integer count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, id.toString());
        return Result.ok(BooleanUtil.isTrue(member));
    }

    @Override
    public Result followCommons(Long id) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getId();

        //  根据key获取共同关注集合
        String key = "follows:" + userId;
        String key2 = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        // 判断是否有共同关注用户对象,没有则返回空集合
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 提取id并根据id获取共同关注的用户
        // 本功能不要求获取的先后顺序
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }
}
